<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blogs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blogs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blogs/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blogs/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/blogs/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/blogs/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/blogs/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="python,">





  <link rel="alternate" href="/blogs/atom.xml" title="恋恋风辰的个人博客" type="application/atom+xml">






<meta name="description" content="python 网络编程和其他语言都是一样的，服务器这块步骤为：1. 创建套接字2. 绑定地址3. 监听该描述符的所有请求4. 有新的请求到了调用accept处理请求 Python Web服务器网关接口（Python Web Server Gateway Interface，简称“WSGI”），可以保证同一个服务器响应不同应用框架的请求，WSGI的出现，让开发者可以将网络框架与网络服务器的选择分隔开">
<meta name="keywords" content="python">
<meta property="og:type" content="article">
<meta property="og:title" content="python学习(九)网络编程学习--简易网站服务器">
<meta property="og:url" content="https://secondtonone1.gitee.io/blogs/2017/09/05/python9/index.html">
<meta property="og:site_name" content="恋恋风辰的个人博客">
<meta property="og:description" content="python 网络编程和其他语言都是一样的，服务器这块步骤为：1. 创建套接字2. 绑定地址3. 监听该描述符的所有请求4. 有新的请求到了调用accept处理请求 Python Web服务器网关接口（Python Web Server Gateway Interface，简称“WSGI”），可以保证同一个服务器响应不同应用框架的请求，WSGI的出现，让开发者可以将网络框架与网络服务器的选择分隔开">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://secondtonone1.gitee.io/blogs/2017/09/05/python9/1.png">
<meta property="og:image" content="https://secondtonone1.gitee.io/blogs/2017/09/05/python9/2.png">
<meta property="og:image" content="https://secondtonone1.gitee.io/blogs/2017/09/05/python9/3.png">
<meta property="og:image" content="https://secondtonone1.gitee.io/blogs/2017/09/05/python9/4.png">
<meta property="og:image" content="https://secondtonone1.gitee.io/blogs/2017/09/05/python9/1.jpg">
<meta property="og:updated_time" content="2020-06-22T09:30:59.086Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="python学习(九)网络编程学习--简易网站服务器">
<meta name="twitter:description" content="python 网络编程和其他语言都是一样的，服务器这块步骤为：1. 创建套接字2. 绑定地址3. 监听该描述符的所有请求4. 有新的请求到了调用accept处理请求 Python Web服务器网关接口（Python Web Server Gateway Interface，简称“WSGI”），可以保证同一个服务器响应不同应用框架的请求，WSGI的出现，让开发者可以将网络框架与网络服务器的选择分隔开">
<meta name="twitter:image" content="https://secondtonone1.gitee.io/blogs/2017/09/05/python9/1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blogs/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://secondtonone1.gitee.io/blogs/2017/09/05/python9/">





  <title>python学习(九)网络编程学习--简易网站服务器 | 恋恋风辰的个人博客</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blogs/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">恋恋风辰的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blogs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blogs/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blogs/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blogs/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Tags
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="Searching..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://secondtonone1.gitee.io/blogs/blogs/2017/09/05/python9/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="恋恋风辰">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blogs/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="恋恋风辰的个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">python学习(九)网络编程学习--简易网站服务器</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-09-05T15:39:49+08:00">
                2017-09-05
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/blogs/categories/python/" itemprop="url" rel="index">
                    <span itemprop="name">python</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>python <code>网络编程</code>和其他语言都是一样的，服务器这块步骤为：<br><code>1. 创建套接字</code><br><code>2. 绑定地址</code><br><code>3. 监听该描述符的所有请求</code><br><code>4. 有新的请求到了调用accept处理请求</code></p>
<p>Python Web服务器网关接口（Python Web Server Gateway Interface，简称<code>“WSGI”</code>），可以保证同一个服务器响应不同应用框架的请求，WSGI的出现，让开发者可以将网络框架与网络服务器的选择分隔开来，例如，你可以使用Gunicorn或Nginx/uWSGI或Waitress服务器来运行Django、Flask或Pyramid应用。下面简单实现一个机遇WSGI协议的服务器。<br><a id="more"></a><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> socket</span><br><span class="line"><span class="keyword">from</span> io <span class="keyword">import</span> StringIO</span><br><span class="line"><span class="keyword">import</span> sys</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">WSGIServer</span><span class="params">(object)</span>:</span></span><br><span class="line"></span><br><span class="line">    address_family = socket.AF_INET</span><br><span class="line">    socket_type = socket.SOCK_STREAM</span><br><span class="line">    request_queue_size = <span class="number">1</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, server_address)</span>:</span></span><br><span class="line">        <span class="comment"># Create a listening socket</span></span><br><span class="line">        self.listen_socket = listen_socket = socket.socket(</span><br><span class="line">            self.address_family,</span><br><span class="line">            self.socket_type</span><br><span class="line">        )</span><br><span class="line">        <span class="comment"># Allow to reuse the same address</span></span><br><span class="line">        listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, <span class="number">1</span>)</span><br><span class="line">        <span class="comment"># Bind</span></span><br><span class="line">        listen_socket.bind(server_address)</span><br><span class="line">        <span class="comment"># Activate</span></span><br><span class="line">        listen_socket.listen(self.request_queue_size)</span><br><span class="line">        <span class="comment"># Get server host name and port</span></span><br><span class="line">        host, port = self.listen_socket.getsockname()[:<span class="number">2</span>]</span><br><span class="line">        self.server_name = socket.getfqdn(host)</span><br><span class="line">        self.server_port = port</span><br><span class="line">        <span class="comment"># Return headers set by Web framework/Web application</span></span><br><span class="line">        self.headers_set = []</span><br></pre></td></tr></table></figure></p>
<p>定义了一个WSGIServer类，并且在类的init函数完成了套接字的创建、绑定、监听等。<br>下面实现WSGIServer的轮询检测新的连接并处理连接：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">set_app</span><span class="params">(self, application)</span>:</span></span><br><span class="line">        self.application = application</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">serve_forever</span><span class="params">(self)</span>:</span></span><br><span class="line">    listen_socket = self.listen_socket</span><br><span class="line">    <span class="keyword">while</span> <span class="keyword">True</span>:</span><br><span class="line">        <span class="comment"># New client connection</span></span><br><span class="line">        self.client_connection, client_address = listen_socket.accept()</span><br><span class="line">        <span class="comment"># Handle one request and close the client connection. Then</span></span><br><span class="line">        <span class="comment"># loop over to wait for another client connection</span></span><br><span class="line">        self.handle_one_request()</span><br></pre></td></tr></table></figure></p>
<p>实现处理请求的函数<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">handle_one_request</span><span class="params">(self)</span>:</span></span><br><span class="line">    self.request_data = request_data = self.client_connection.recv(<span class="number">1024</span>)</span><br><span class="line">    <span class="comment"># Print formatted request data a la 'curl -v'</span></span><br><span class="line">    print(<span class="string">''</span>.join(</span><br><span class="line">            <span class="string">'&lt; &#123;line&#125;\n'</span>.format(line=line)</span><br><span class="line">            <span class="keyword">for</span> line <span class="keyword">in</span> request_data.splitlines()</span><br><span class="line">    ))</span><br><span class="line"></span><br><span class="line">    self.parse_request(request_data)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># Construct environment dictionary using request data</span></span><br><span class="line">    env = self.get_environ()</span><br><span class="line"></span><br><span class="line">    <span class="comment"># It's time to call our application callable and get</span></span><br><span class="line">    <span class="comment"># back a result that will become HTTP response body</span></span><br><span class="line">    result = self.application(env, self.start_response)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># Construct a response and send it back to the client</span></span><br><span class="line">    self.finish_response(result)</span><br></pre></td></tr></table></figure></p>
<p>解析请求<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">parse_request</span><span class="params">(self, text)</span>:</span></span><br><span class="line">    request_line = text.splitlines()[<span class="number">0</span>]</span><br><span class="line">    request_line = request_line.rstrip(<span class="string">'\r\n'</span>)</span><br><span class="line">    <span class="comment"># Break down the request line into components</span></span><br><span class="line">    (self.request_method,  <span class="comment"># GET</span></span><br><span class="line">    self.path,            <span class="comment"># /hello</span></span><br><span class="line">    self.request_version  <span class="comment"># HTTP/1.1</span></span><br><span class="line">    ) = request_line.split()</span><br></pre></td></tr></table></figure></p>
<p>返回当前服务器wsgi版本等信息<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_environ</span><span class="params">(self)</span>:</span></span><br><span class="line">    env = &#123;&#125;</span><br><span class="line">    <span class="comment"># The following code snippet does not follow PEP8 conventions</span></span><br><span class="line">    <span class="comment"># but it's formatted the way it is for demonstration purposes</span></span><br><span class="line">    <span class="comment"># to emphasize the required variables and their values</span></span><br><span class="line">    <span class="comment">#</span></span><br><span class="line">    <span class="comment"># Required WSGI variables</span></span><br><span class="line">    env[<span class="string">'wsgi.version'</span>]      = (<span class="number">1</span>, <span class="number">0</span>)</span><br><span class="line">    env[<span class="string">'wsgi.url_scheme'</span>]   = <span class="string">'http'</span></span><br><span class="line">    env[<span class="string">'wsgi.input'</span>]        = StringIO.StringIO(self.request_data)</span><br><span class="line">    env[<span class="string">'wsgi.errors'</span>]       = sys.stderr</span><br><span class="line">    env[<span class="string">'wsgi.multithread'</span>]  = <span class="keyword">False</span></span><br><span class="line">    env[<span class="string">'wsgi.multiprocess'</span>] = <span class="keyword">False</span></span><br><span class="line">    env[<span class="string">'wsgi.run_once'</span>]     = <span class="keyword">False</span></span><br><span class="line">    <span class="comment"># Required CGI variables</span></span><br><span class="line">    env[<span class="string">'REQUEST_METHOD'</span>]    = self.request_method    <span class="comment"># GET</span></span><br><span class="line">    env[<span class="string">'PATH_INFO'</span>]         = self.path              <span class="comment"># /hello</span></span><br><span class="line">    env[<span class="string">'SERVER_NAME'</span>]       = self.server_name       <span class="comment"># localhost</span></span><br><span class="line">    env[<span class="string">'SERVER_PORT'</span>]       = str(self.server_port)  <span class="comment"># 8888</span></span><br><span class="line">    <span class="keyword">return</span> env</span><br></pre></td></tr></table></figure></p>
<p>填写app所需的回调函数<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">start_response</span><span class="params">(self, status, response_headers, exc_info=None)</span>:</span></span><br><span class="line">    <span class="comment"># Add necessary server headers</span></span><br><span class="line">    server_headers = [</span><br><span class="line">            (<span class="string">'Date'</span>, <span class="string">'Tue, 31 Mar 2015 12:54:48 GMT'</span>),</span><br><span class="line">            (<span class="string">'Server'</span>, <span class="string">'WSGIServer 0.2'</span>),</span><br><span class="line">    ]</span><br><span class="line">    self.headers_set = [status, response_headers + server_headers]</span><br><span class="line">    <span class="comment"># To adhere to WSGI specification the start_response must return</span></span><br><span class="line">    <span class="comment"># a 'write' callable. We simplicity's sake we'll ignore that detail</span></span><br><span class="line">    <span class="comment"># for now.</span></span><br><span class="line">    <span class="comment"># return self.finish_response</span></span><br></pre></td></tr></table></figure></p>
<p>发送数据并且关闭连接<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">finish_response</span><span class="params">(self, result)</span>:</span></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        status, response_headers = self.headers_set</span><br><span class="line">        response = <span class="string">'HTTP/1.1 &#123;status&#125;\r\n'</span>.format(status=status)</span><br><span class="line">        <span class="keyword">for</span> header <span class="keyword">in</span> response_headers:</span><br><span class="line">            response += <span class="string">'&#123;0&#125;: &#123;1&#125;\r\n'</span>.format(*header)</span><br><span class="line">        response += <span class="string">'\r\n'</span></span><br><span class="line">        <span class="keyword">for</span> data <span class="keyword">in</span> result:</span><br><span class="line">            response += data</span><br><span class="line">            <span class="comment"># Print formatted response data a la 'curl -v'</span></span><br><span class="line">        print(<span class="string">''</span>.join(</span><br><span class="line">                <span class="string">'&gt; &#123;line&#125;\n'</span>.format(line=line)</span><br><span class="line">                 <span class="keyword">for</span> line <span class="keyword">in</span> response.splitlines()</span><br><span class="line">        ))</span><br><span class="line">        self.client_connection.sendall(response)</span><br><span class="line">    <span class="keyword">finally</span>:</span><br><span class="line">        self.client_connection.close()</span><br></pre></td></tr></table></figure></p>
<p>主函数和参数解析，创建服务器<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">SERVER_ADDRESS = (HOST, PORT) = <span class="string">''</span>, <span class="number">8888</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">make_server</span><span class="params">(server_address, application)</span>:</span></span><br><span class="line">    server = WSGIServer(server_address)</span><br><span class="line">    server.set_app(application)</span><br><span class="line">    <span class="keyword">return</span> server</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    <span class="keyword">if</span> len(sys.argv) &lt; <span class="number">2</span>:</span><br><span class="line">        sys.exit(<span class="string">'Provide a WSGI application object as module:callable'</span>)</span><br><span class="line">    app_path = sys.argv[<span class="number">1</span>]</span><br><span class="line">    module, application = app_path.split(<span class="string">':'</span>)</span><br><span class="line">    module = __import__(module)</span><br><span class="line">    application = getattr(module, application)</span><br><span class="line">    httpd = make_server(SERVER_ADDRESS, application)</span><br><span class="line">    print(<span class="string">'WSGIServer: Serving HTTP on port &#123;port&#125; ...\n'</span>.format(port=PORT))</span><br><span class="line">    httpd.serve_forever()</span><br></pre></td></tr></table></figure></p>
<p>将上面的文件保存为webserver.py<br>下面搭建虚拟环境，并且安装Pyramid、Flask和Django等框架开发的网络应用。<br><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">$</span><span class="bash"> [sudo] pip install virtualenv</span></span><br><span class="line"><span class="meta">$</span><span class="bash"> mkdir ~/envs</span></span><br><span class="line"><span class="meta">$</span><span class="bash"> virtualenv ~/envs/lsbaws/</span></span><br><span class="line"><span class="meta">$</span><span class="bash"> <span class="built_in">cd</span> ~/envs/lsbaws/</span></span><br><span class="line"><span class="meta">$</span><span class="bash"> ls</span></span><br><span class="line">bin  include  lib</span><br><span class="line"><span class="meta">$</span><span class="bash"> <span class="built_in">source</span> bin/activate</span></span><br><span class="line">(lsbaws) $ pip install pyramid</span><br><span class="line">(lsbaws) $ pip install flask</span><br><span class="line">(lsbaws) $ pip install django</span><br></pre></td></tr></table></figure></p>
<p>编写pyramidapp.py，主要是调用pyramidapp接口生成app<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> pyramid.config <span class="keyword">import</span> Configurator</span><br><span class="line"><span class="keyword">from</span> pyramid.response <span class="keyword">import</span> Response</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">hello_world</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> Response(</span><br><span class="line">        <span class="string">'Hello world from Pyramid!\n'</span>,</span><br><span class="line">        content_type=<span class="string">'text/plain'</span>,</span><br><span class="line">    )</span><br><span class="line"></span><br><span class="line">config = Configurator()</span><br><span class="line">config.add_route(<span class="string">'hello'</span>, <span class="string">'/hello'</span>)</span><br><span class="line">config.add_view(hello_world, route_name=<span class="string">'hello'</span>)</span><br><span class="line">app = config.make_wsgi_app()</span><br></pre></td></tr></table></figure></p>
<p>可以通过自己开发的网络服务器来启动上面的Pyramid应用。<br><code>python webserver.py pyramidapp:app</code></p>
<p><img src="1.png" alt="1.png"><br><img src="2.png" alt="2.png"><br>同样可以创建Flask应用<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> flask <span class="keyword">import</span> Flask</span><br><span class="line"><span class="keyword">from</span> flask <span class="keyword">import</span> Response</span><br><span class="line">flask_app = Flask(<span class="string">'flaskapp'</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@flask_app.route('/hello')</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">hello_world</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">return</span> Response(</span><br><span class="line">        <span class="string">'Hello world from Flask!\n'</span>,</span><br><span class="line">        mimetype=<span class="string">'text/plain'</span></span><br><span class="line">    )</span><br><span class="line"></span><br><span class="line">app = flask_app.wsgi_app</span><br></pre></td></tr></table></figure></p>
<p><img src="3.png" alt="3.png"></p>
<p>上述代码的工作原理：</p>
<p><code>1 网络框架提供一个命名为application的可调用对象</code>。<br><code>2 服务器每次从HTTP客户端接收请求之后，调用application。它会向可调用对象传递一个名叫environ的字典作为参数，其中包含了WSGI/CGI的诸多变量，以及一个名为start_response的可调用对象</code>。<br><code>3 框架/应用生成HTTP状态码以及HTTP响应报头（HTTP response headers），然后将二者传递至start_response，等待服务器保存。此外，框架/应用还将返回响应的正文。
服务器将状态码、响应报头和响应正文组合成HTTP响应，并返回给客户端</code>。</p>
<p>可以采用多进程的方式处理多个客户端请求,将上述代码稍作修改<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> errno</span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"><span class="keyword">import</span> signal</span><br><span class="line"><span class="keyword">import</span> socket</span><br><span class="line"></span><br><span class="line">SERVER_ADDRESS = (HOST, PORT) = <span class="string">''</span>, <span class="number">8888</span></span><br><span class="line">REQUEST_QUEUE_SIZE = <span class="number">1024</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">grim_reaper</span><span class="params">(signum, frame)</span>:</span></span><br><span class="line">    <span class="keyword">while</span> <span class="keyword">True</span>:</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            pid, status = os.waitpid(</span><br><span class="line">                <span class="number">-1</span>,          <span class="comment"># Wait for any child process</span></span><br><span class="line">                 os.WNOHANG  <span class="comment"># Do not block and return EWOULDBLOCK error</span></span><br><span class="line">            )</span><br><span class="line">        <span class="keyword">except</span> OSError:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> pid == <span class="number">0</span>:  <span class="comment"># no more zombies</span></span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">handle_request</span><span class="params">(client_connection)</span>:</span></span><br><span class="line">    request = client_connection.recv(<span class="number">1024</span>)</span><br><span class="line">    print(request.decode())</span><br><span class="line">    http_response = <span class="string">b"""\</span></span><br><span class="line"><span class="string">HTTP/1.1 200 OK</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">Hello, World!</span></span><br><span class="line"><span class="string">"""</span></span><br><span class="line">    client_connection.sendall(http_response)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">serve_forever</span><span class="params">()</span>:</span></span><br><span class="line">    listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)</span><br><span class="line">    listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, <span class="number">1</span>)</span><br><span class="line">    listen_socket.bind(SERVER_ADDRESS)</span><br><span class="line">    listen_socket.listen(REQUEST_QUEUE_SIZE)</span><br><span class="line">    print(<span class="string">'Serving HTTP on port &#123;port&#125; ...'</span>.format(port=PORT))</span><br><span class="line"></span><br><span class="line">    signal.signal(signal.SIGCHLD, grim_reaper)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">while</span> <span class="keyword">True</span>:</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            client_connection, client_address = listen_socket.accept()</span><br><span class="line">        <span class="keyword">except</span> IOError <span class="keyword">as</span> e:</span><br><span class="line">            code, msg = e.args</span><br><span class="line">            <span class="comment"># restart 'accept' if it was interrupted</span></span><br><span class="line">            <span class="keyword">if</span> code == errno.EINTR:</span><br><span class="line">                <span class="keyword">continue</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="keyword">raise</span></span><br><span class="line"></span><br><span class="line">        pid = os.fork()</span><br><span class="line">        <span class="keyword">if</span> pid == <span class="number">0</span>:  <span class="comment"># child</span></span><br><span class="line">            listen_socket.close()  <span class="comment"># close child copy</span></span><br><span class="line">            handle_request(client_connection)</span><br><span class="line">            client_connection.close()</span><br><span class="line">            os._exit(<span class="number">0</span>)</span><br><span class="line">        <span class="keyword">else</span>:  <span class="comment"># parent</span></span><br><span class="line">            client_connection.close()  <span class="comment"># close parent copy and loop over</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    serve_forever()</span><br></pre></td></tr></table></figure></p>
<p>grim_reaper 函数为捕捉子进程退出的回调函数，父进程等待所有子进程退出后再退出，避免僵尸进程。由于子进程退出父进程捕获到消息，调用grim_reaper处理，由于父进程之前阻塞在accept上，捕获子进程销毁消息后，父进程accept失败，所以增加了errno.EINTR错误判断，如果是由于信号中断导致accept失败，就让父进程继续调用accept即可。</p>
<p><img src="4.png" alt="4.png"><br>谢谢关注我的微信公众平台：<br><img src="1.jpg" alt="1.jpg"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blogs/tags/python/" rel="tag"># python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blogs/2017/08/31/python8/" rel="next" title="python学习(八)定制类和枚举">
                <i class="fa fa-chevron-left"></i> python学习(八)定制类和枚举
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blogs/2017/09/07/python10/" rel="prev" title="python学习(十)元类学习和应用">
                python学习(十)元类学习和应用 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">恋恋风辰</p>
              <p class="site-description motion-element" itemprop="description">重剑无锋，大巧不工</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blogs/archives/">
              
                  <span class="site-state-item-count">146</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blogs/categories/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blogs/tags/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blogs/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/secondtonone1" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/wang-wu-chen-32/activities" target="_blank" title="ZhiHu">
                    
                      <i class="fa fa-fw fa-ZhiHu"></i>ZhiHu</a>
                </span>
              
            
          </div>

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">恋恋风辰</span>

  
  
 
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
    <span class="post-meta-divider">|</span>
    <span id="busuanzi_container_site_uv">本站访客数<span id="busuanzi_value_site_uv"></span>人</span>
 
 
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.3</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blogs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blogs/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/blogs/js/src/motion.js?v=5.1.3"></script>



  
  

  
  <script type="text/javascript" src="/blogs/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/blogs/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/blogs/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blogs/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
